<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Mybatis," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="概述 我们知道，一个框架的运行，往往都从配置文件的加载开始，本篇文章作为 Mybatis 源码学习的第一篇文章，将结合源码，阐述 Mybatis 是如何加载 mybatis-config.xml 配置文件的。 Mybatis 版本：3.5.8 JDK 版本：1.8 Mysql 版本：5.6.51 一、输入流的读取 我们根据源码给的测试用例，可以知道 Mybatis 可以通过以下代码获取 Xml 配">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis源码学习（一）：配置文件的加载">
<meta property="og:url" content="http://blog.xiajibagao.top/2021/06/05/mybatis/Mybatis%E6%BA%90%E7%A0%81%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9A%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%9A%84%E5%8A%A0%E8%BD%BD/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="概述 我们知道，一个框架的运行，往往都从配置文件的加载开始，本篇文章作为 Mybatis 源码学习的第一篇文章，将结合源码，阐述 Mybatis 是如何加载 mybatis-config.xml 配置文件的。 Mybatis 版本：3.5.8 JDK 版本：1.8 Mysql 版本：5.6.51 一、输入流的读取 我们根据源码给的测试用例，可以知道 Mybatis 可以通过以下代码获取 Xml 配">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/image-20210602102537931.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20210603100220028.png">
<meta property="article:published_time" content="2021-06-04T16:00:00.000Z">
<meta property="article:modified_time" content="2021-06-21T14:44:39.088Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="Mybatis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/image-20210602102537931.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2021/06/05/mybatis/Mybatis源码学习（一）：配置文件的加载/"/>





  <title>Mybatis源码学习（一）：配置文件的加载 | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2021/06/05/mybatis/Mybatis%E6%BA%90%E7%A0%81%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9A%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%9A%84%E5%8A%A0%E8%BD%BD/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Mybatis源码学习（一）：配置文件的加载</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-06-05T00:00:00+08:00">
                2021-06-05
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Mybatis/" itemprop="url" rel="index">
                    <span itemprop="name">Mybatis</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.5k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述">概述</h2>
<p>我们知道，一个框架的运行，往往都从配置文件的加载开始，本篇文章作为 Mybatis 源码学习的第一篇文章，将结合源码，阐述 Mybatis 是如何加载 mybatis-config.xml 配置文件的。</p>
<p>Mybatis 版本：3.5.8</p>
<p>JDK 版本：1.8</p>
<p>Mysql 版本：5.6.51</p>
<h2 id="一-输入流的读取">一、输入流的读取</h2>
<p>我们根据源码给的测试用例，可以知道 Mybatis 可以通过以下代码获取 Xml 配置文件并转为配置类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">String resource = <span class="string">&quot;org/apache/ibatis/builder/MinimalMapperConfig.xml&quot;</span>;</span><br><span class="line"><span class="keyword">try</span> (InputStream inputStream = Resources.getResourceAsStream(resource)) &#123;</span><br><span class="line">    XMLConfigBuilder builder = <span class="keyword">new</span> XMLConfigBuilder(inputStream);</span><br><span class="line">    Configuration config = builder.parse();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>拿到全局配置类 <code>Configuration</code> 以后就可以通过<code>SqlSessionFactoryBuilder().build()</code>方法去创建<code>SqlSessionFactory</code>了。当然，<code>SqlSessionFactoryBuilder().build()</code>有多个重载方法，但是无外乎都要经过转换为 <code>Configuration</code> 这一步。</p>
<p>整个过程就分为三步：</p>
<ol>
<li>获取配置文件输入流：<code>getResourceAsStream()</code></li>
<li>解析得到配置文件：<code>XMLConfigBuilder</code></li>
<li>将解析得到的结果转为配置类：<code>XMLConfigBuilder.parse()</code></li>
</ol>
<h3 id="1程序入口">1.程序入口</h3>
<p>点进<code>Resources.getResourceAsStream(resource)</code>，发现它是一个重载方法，原本的方法是需要传入 <code>ClassLoader</code> 的，但是这里直接传了个 null：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> InputStream <span class="title">getResourceAsStream</span><span class="params">(String resource)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> getResourceAsStream(<span class="keyword">null</span>, resource);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 被重载的方法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> InputStream <span class="title">getResourceAsStream</span><span class="params">(ClassLoader loader, String resource)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);</span><br><span class="line">    <span class="keyword">if</span> (in == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IOException(<span class="string">&quot;Could not find resource &quot;</span> + resource);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> in;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个方法实际依赖于<code>classLoaderWrapper.getResourceAsStream(resource, loader)</code>方法，而<code>classLoaderWrapper</code>是一个 Resources 中的一个使用饿汉式单例化的成员变量：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> ClassLoaderWrapper classLoaderWrapper = <span class="keyword">new</span> ClassLoaderWrapper();</span><br></pre></td></tr></table></figure>
<p>在整个<code>Resources</code>类中，几乎绝大部分的输入流都通过 <code>ClassLoaderWrapper</code>的方法进行读取。</p>
<h3 id="2classloaderwrapper">2.ClassLoaderWrapper</h3>
<p><code>ClassLoaderWrapper</code>是一个类加载器的包装器，包含了多个类加载器，当我们使用时，它会按顺序检查类加载器是否为目标加载器，我们可以通过它去加载资源而不必考虑加载器的正确性问题。</p>
<p><img src="http://img.xiajibagao.top/image-20210602102537931.png" alt="image-20210602102537931"></p>
<p>他的成员变量主要有两个：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 默认类加载器</span></span><br><span class="line">ClassLoader defaultClassLoader;</span><br><span class="line"><span class="comment">// 系统加载器</span></span><br><span class="line">ClassLoader systemClassLoader; </span><br><span class="line"></span><br><span class="line">ClassLoaderWrapper() &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 系统加载器在类包装类创建时直接获取</span></span><br><span class="line">        systemClassLoader = ClassLoader.getSystemClassLoader();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (SecurityException ignored) &#123;</span><br><span class="line">        <span class="comment">// AccessControlException on Google App Engine</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中系统加载器在类包装类创建时直接获取，而默认加载器由外部类调用时去设置。</p>
<p>他主要提供了三种获取资源的方法：</p>
<ul>
<li>获取 url：<code>getResourceAsURL()</code></li>
<li>获取输入流：<code>getResourceAsStream()</code></li>
<li>获取类：<code>classForName()</code></li>
</ul>
<h3 id="3获取输入流">3.获取输入流</h3>
<p>我们以<code>getResourceAsStream(String resource, ClassLoader classLoader)</code>为例，看看他是如何实现的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> InputStream <span class="title">getResourceAsStream</span><span class="params">(String resource, ClassLoader classLoader)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 先通过 getClassLoaders(classLoader) 获取类加载器</span></span><br><span class="line">    <span class="comment">// 再通过 getResourceAsStream(resource, classLoader) 获取输入流</span></span><br><span class="line">    <span class="keyword">return</span> getResourceAsStream(resource, getClassLoaders(classLoader));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中，<code>getClassLoaders(classLoader)</code>方法主要用于获取按顺序获取一组类加载器，同时会把参数传入的自定义类加载器类加载器插到最前面：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">ClassLoader[] getClassLoaders(ClassLoader classLoader) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ClassLoader[]&#123;</span><br><span class="line">        classLoader, <span class="comment">// 自定义类加载器</span></span><br><span class="line">        defaultClassLoader, <span class="comment">// 默认类加载器</span></span><br><span class="line">        Thread.currentThread().getContextClassLoader(), <span class="comment">// 线程上下文类加载器</span></span><br><span class="line">        getClass().getClassLoader(), <span class="comment">// ClassLoaderWrapper的类加载器</span></span><br><span class="line">        systemClassLoader&#125;;<span class="comment">// 系统加载器</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接着，拿到一组 <code>ClassLoader</code> 以后，再去执行 <code>getResourceAsStream(String resource, ClassLoader[] classLoader)</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">InputStream <span class="title">getResourceAsStream</span><span class="params">(String resource, ClassLoader[] classLoader)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 遍历类加载器，执行非空加载器</span></span><br><span class="line">    <span class="keyword">for</span> (ClassLoader cl : classLoader) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">null</span> != cl) &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 读取输入流</span></span><br><span class="line">            InputStream returnValue = cl.getResourceAsStream(resource);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 如果拿不到，尝试改个路径再试试</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> == returnValue) &#123;</span><br><span class="line">                returnValue = cl.getResourceAsStream(<span class="string">&quot;/&quot;</span> + resource);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 如果能获取到输入流，说明需要的类加载器已经找到了，直接终止循环返回输入流</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> != returnValue) &#123;</span><br><span class="line">                <span class="keyword">return</span> returnValue;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4总体流程">4.总体流程</h3>
<p>综合以上步骤，当我们调用<code>Resources.getResourceAsStream()</code>方法时，整个流程其实是这样的：</p>
<ul>
<li>先调用<code>getClassLoaders()</code>方法，获取一个类加载数组；</li>
<li>类加载数组按顺序放入传入的自定义类加载器、默认类加载器、线程上下文类加载器、<code>ClassLoaderWrapper</code>的类加载器、系统加载器；</li>
<li>遍历类加载器数组，使用类加载器根据传入路径加载资源，如果其中一个能加载到资源，就不再使用后面的加载器。</li>
<li>返回输入流。</li>
</ul>
<p>以上流程同样使用于<code>classForName()</code>或者<code>getResourceAsURL()</code>。</p>
<p>也不难看出，<code>Resouces</code>这个类实际上就是在 <code>ClassLoaderWrapper</code> 的基础上对获取到的结果进行进一步处理，比如把输入流转为 Reader 或者文件再返回。</p>
<p>至此，我们读取到了配置文件。</p>
<h2 id="二-输入流的解析">二、输入流的解析</h2>
<p><strong>资源加载主要的包都在 <code>org.apache.ibatis.parsing</code>包下。</strong></p>
<p>当我们获取到配置文件以后，解析并将其转为<code>XMLConfigBuilder</code>类，他的构造函数很多，我们以<code>XMLConfigBuilder(InputStream inputStream)</code>为例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">XMLConfigBuilder</span><span class="params">(InputStream inputStream)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>(inputStream, <span class="keyword">null</span>, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">XMLConfigBuilder</span><span class="params">(Reader reader, String environment, Properties props)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 创建一个XPathParser</span></span><br><span class="line">    <span class="keyword">this</span>(<span class="keyword">new</span> XPathParser(reader, <span class="keyword">true</span>, props, <span class="keyword">new</span> XMLMapperEntityResolver()), environment, props);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 全参构造函数</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="title">XMLConfigBuilder</span><span class="params">(XPathParser parser, String environment, Properties props)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 初始化一个具有默认参数的Configuration</span></span><br><span class="line">    <span class="keyword">super</span>(<span class="keyword">new</span> Configuration());</span><br><span class="line">    </span><br><span class="line">    ErrorContext.instance().resource(<span class="string">&quot;SQL Mapper Configuration&quot;</span>);</span><br><span class="line">    <span class="keyword">this</span>.configuration.setVariables(props);</span><br><span class="line">    <span class="keyword">this</span>.parsed = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">this</span>.environment = environment;</span><br><span class="line">    <span class="keyword">this</span>.parser = parser;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到，<code>XMLConfigBuilder</code>创建实际上也分为两部分：</p>
<ul>
<li>初始化一个 <code>XPathParser</code>用于后续解析；</li>
<li>初始一个具有基本参数的 <code>Configuration</code></li>
</ul>
<h3 id="1xpathparser">1.XPathParser</h3>
<p><code>XPathParser</code>类看名字，很容易知道这是一个解析类，他的构造函数还需要传入一个 <code>XMLMapperEntityResolver</code>。</p>
<p>关于<code>XMLMapperEntityResolver</code>这个类，他实现了 <code>java.io.EntityResolver</code>接口，这个接口的作用如下：</p>
<blockquote>
<p>对于解析一个 SAX 文件，程序首先会读取该 Xml 文档上的声明，根据声明去寻找相应的 DTD 声明，以便对文档格式的进行验证。</p>
<p>默认的寻找规则即通过实现上声明的 DTD 的 URI 地址来下载DTD声明，但是当相应的 DTD 没找到就会报错，所以理想情况是我们直接在本地放一个 DTD 文件，程序加载时直接去本地对应的地址加载。而 EntityResolver 的接口作用就是规定程序如何去寻找 DTD 。</p>
<p>当我们实现接口的 <code>setEntityResolver()</code> 并向 SAX 驱动器注册一个实例后，程序就会有有限根据 SAX 驱动器里面的规则进行寻址。</p>
</blockquote>
<p>而<code>XMLMapperEntityResolver</code>里面就规定了程序如何去指定位置找到 Mybatis 的 DTD 文件，比如 Mybaits 的配置文件与 Mapper 文件就在这两个常量：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String MYBATIS_CONFIG_DTD = <span class="string">&quot;org/apache/ibatis/builder/xml/mybatis-3-config.dtd&quot;</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String MYBATIS_MAPPER_DTD = <span class="string">&quot;org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd&quot;</span>;</span><br></pre></td></tr></table></figure>
<p>接着，在构建 xml 解析器 <code>XPathParser</code>的时候，放入<code>XMLMapperEntityResolver</code>与输入流以及其他必要参数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">XPathParser parser = <span class="keyword">new</span> XPathParser(inputStream, <span class="keyword">true</span>, <span class="keyword">null</span>, <span class="keyword">new</span> XMLMapperEntityResolver());</span><br></pre></td></tr></table></figure>
<p>此时 <code>XPathParser</code>  实例完成初始化，输入流的 XML 文件被解析为 <code>dom</code> 树并存放在了一个 <code>org.w3c.dom.Document</code>类型的成员变量 <code>document</code>中，通过内部提供 <code>evalNode()</code>方法可以解析为节点 <code>XNode</code> 实例，通过对 <code>XNode</code> 类型的节点进一步解析，使用 <code>evalXXX()</code>为开口的各种方法解析处对应的数据。</p>
<p>关于 <code>XPathParser</code>，更具体的可以参考<a target="_blank" rel="noopener" href="https://blog.csdn.net/hou_ge/article/details/100179262">Mybatis源码学习(5)-解析器模块之XNode、XPathParser_向心行者-CSDN博客</a>。</p>
<h3 id="2xmlconfigbuilder">2.XMLConfigBuilder</h3>
<p><code>XMLConfigBuilder</code>类内部提供诸如<code>dataSourceElement()</code>这类 <code>XXXElement()</code>的方法去直接获取指定的一组标签数据，通过针对配置文件的各个节点的解析，最终得到完整的配置文件数据。</p>
<p>整个逻辑看起来不简单，实际上对应的代码就两行：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">XMLConfigBuilder builder = <span class="keyword">new</span> XMLConfigBuilder(inputStream);</span><br><span class="line">Configuration config = builder.parse();</span><br></pre></td></tr></table></figure>
<p>其中 <code>parse()</code>方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Configuration <span class="title">parse</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 转换一次以后就不允许转换第二次了</span></span><br><span class="line">    <span class="keyword">if</span> (parsed) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BuilderException(<span class="string">&quot;Each XMLConfigBuilder can only be used once.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    parsed = <span class="keyword">true</span>;</span><br><span class="line">    parseConfiguration(parser.evalNode(<span class="string">&quot;/configuration&quot;</span>));</span><br><span class="line">    <span class="keyword">return</span> configuration;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实际上调用的是 <code>parseConfiguration()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">parseConfiguration</span><span class="params">(XNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        propertiesElement(root.evalNode(<span class="string">&quot;properties&quot;</span>));</span><br><span class="line">        Properties settings = settingsAsProperties(root.evalNode(<span class="string">&quot;settings&quot;</span>));</span><br><span class="line">        loadCustomVfs(settings);</span><br><span class="line">        loadCustomLogImpl(settings);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 加载自定义的别名与类的映射关系</span></span><br><span class="line">        typeAliasesElement(root.evalNode(<span class="string">&quot;typeAliases&quot;</span>));</span><br><span class="line">        <span class="comment">// 加载定义拦截器插件</span></span><br><span class="line">        pluginElement(root.evalNode(<span class="string">&quot;plugins&quot;</span>));</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 加载自定义实例工厂</span></span><br><span class="line">        objectFactoryElement(root.evalNode(<span class="string">&quot;objectFactory&quot;</span>));</span><br><span class="line">        <span class="comment">// 加载自定义实例包装类工厂</span></span><br><span class="line">        objectWrapperFactoryElement(root.evalNode(<span class="string">&quot;objectWrapperFactory&quot;</span>));</span><br><span class="line">        <span class="comment">// 加载自定义反射工厂</span></span><br><span class="line">        reflectorFactoryElement(root.evalNode(<span class="string">&quot;reflectorFactory&quot;</span>));</span><br><span class="line">        settingsElement(settings);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 加载环境变量</span></span><br><span class="line">        environmentsElement(root.evalNode(<span class="string">&quot;environments&quot;</span>));</span><br><span class="line">        <span class="comment">// 加载数据库标识符</span></span><br><span class="line">        databaseIdProviderElement(root.evalNode(<span class="string">&quot;databaseIdProvider&quot;</span>));</span><br><span class="line">        <span class="comment">// 加载自定义类型和处理器</span></span><br><span class="line">        typeHandlerElement(root.evalNode(<span class="string">&quot;typeHandlers&quot;</span>));</span><br><span class="line">        <span class="comment">// 加载mapepr接口</span></span><br><span class="line">        mapperElement(root.evalNode(<span class="string">&quot;mappers&quot;</span>));</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BuilderException(<span class="string">&quot;Error parsing SQL Mapper Configuration. Cause: &quot;</span> + e, e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这些数据最终被解析至它的内部变量 <code>configuration</code>中，也就是<code>parse()</code>获取到的对象。</p>
<h2 id="总结">总结</h2>
<p><img src="http://img.xiajibagao.top/image-20210603100220028.png" alt="image-20210603100220028"></p>
<p>当 Mybatis 获取配置文件的主要流程如下：</p>
<p>1.配置读取阶段</p>
<ul>
<li>通过 <code>Resources</code> 获取文件输入流；</li>
<li><code>Resources</code>内部维护了一个 <code>ClassLoaderWrapper</code> 实例，通过<code>ClassLoaderWrapper</code>  先调用<code>getClassLoaders()</code>方法，获取一个类加载数组；</li>
<li>类加载数组按顺序放入传入的自定义类加载器、默认类加载器、线程上下文类加载器、<code>ClassLoaderWrapper</code>的类加载器、系统加载器；</li>
<li>遍历类加载器数组，使用类加载器根据传入路径加载资源，如果其中一个能加载到资源，就不再使用后面的加载器。</li>
<li>返回输入流。</li>
</ul>
<p>2.配置解析阶段</p>
<ul>
<li>通过<code>XMLConfigBuilder</code>去解析文件输入流；</li>
<li><code>XMLConfigBuilder</code>内部维护了<code>XPathParser</code>作为解析器，并通过<code>XMLMapperEntityResolver</code>指定解析器寻找的 DTD 文件路径；</li>
<li>解析器将 Xml 文件解析为标签树；</li>
<li><code>XMLConfigBuilder</code>根据标签名，通过解析器获取相关配置，并放入<code>configuration</code>配置类；</li>
<li>返回配置类。</li>
</ul>
<p>值得一提的是，这里面提到了<code>XPathParser</code>这么个工具类，理论上只要自己通过 DTD 规定一下 Xml 文件格式，我们也能自己 DIY 一下配置文件读取器。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mybatis/" rel="tag"># Mybatis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/02/11/%E5%A4%9A%E7%BA%BF%E7%A8%8B/AQS%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" rel="next" title="AQS源码分析">
                <i class="fa fa-chevron-left"></i> AQS源码分析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/06/14/mybatis/Mybatis%E6%BA%90%E7%A0%81%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9AMapper%E6%8E%A5%E5%8F%A3%E7%9A%84%E7%BB%91%E5%AE%9A/" rel="prev" title="Mybatis源码学习（二）：Mapper接口的绑定">
                Mybatis源码学习（二）：Mapper接口的绑定 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-%E8%BE%93%E5%85%A5%E6%B5%81%E7%9A%84%E8%AF%BB%E5%8F%96"><span class="nav-text">一、输入流的读取</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E7%A8%8B%E5%BA%8F%E5%85%A5%E5%8F%A3"><span class="nav-text">1.程序入口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2classloaderwrapper"><span class="nav-text">2.ClassLoaderWrapper</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E8%8E%B7%E5%8F%96%E8%BE%93%E5%85%A5%E6%B5%81"><span class="nav-text">3.获取输入流</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E6%80%BB%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="nav-text">4.总体流程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-%E8%BE%93%E5%85%A5%E6%B5%81%E7%9A%84%E8%A7%A3%E6%9E%90"><span class="nav-text">二、输入流的解析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1xpathparser"><span class="nav-text">1.XPathParser</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2xmlconfigbuilder"><span class="nav-text">2.XMLConfigBuilder</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
